package com.dexter.year2023.charpter1_linkedlist.level1;

/**
 * 链表的创建，以int数组为例
 *
 * @author Dexter
 */
public class Demo1 {
    /**
     * 创建结点，我的代码里一律写作Node
     */
    public static class Node {
        public int val;
        public Node next;

        public Node(int x) {
            val = x;
            next = null;
        }
    }

    /**
     * 链表初始化
     *
     * @param array
     * @return
     */
    public static Node initLinkedList(int[] array) {
        Node head = null, cur = null;
        for (int i = 0; i < array.length; i++) {
            // 创建新结点
            Node newNode = new Node(array[i]);
            newNode.next = null;
            if (i == 0) {
                head = newNode;
                // 当前结点移动一位，到新结点处
                cur = newNode;
            } else {
                cur.next = newNode;
                cur = newNode;
            }
        }
        // 创建完成，返回头结点
        return head;
    }

    /**
     * 打印链表
     *
     * @param head
     */
    public static void printLinkedList(Node head) {
        StringBuilder sb = new StringBuilder();
        while (head != null) {
            sb.append(head.val);
            if (head.next != null) {
                sb.append(",");
            }
            head = head.next;
        }
        System.out.println(sb.toString());
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        Node head = initLinkedList(a);
        // 打印链表
        printLinkedList(head);
    }
}
